import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { ApiResToComponent } from '@basic';
import { SFSchema } from '@delon/form';
import { BaseOfSystemForm } from '@routes/system/_base';
import { UserForm, UserVO } from '@types';
import { Observable } from 'rxjs';

import { ADD_USER_SCHEMA, EDIT_USER_SCHEMA, RESET_USER_PASSWORD_SCHEMA } from '../edit-user/schema';
import { SystemUserService } from '../user.service';

@Component({
    selector: 'app-system-edit-user',
    templateUrl: './edit-user.component.html',
    styleUrls: ['./edit-user.component.less'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SystemEditUserComponent extends BaseOfSystemForm<UserForm, UserVO> implements OnInit {
    schema!: SFSchema;

    constructor(
        protected override injector: Injector,
        protected userSrv: SystemUserService
    ) {
        super(injector);
    }

    schemaMap: Map<string, SFSchema> = new Map<string, SFSchema>([
        ['add', ADD_USER_SCHEMA(this.injector)],
        ['edit', EDIT_USER_SCHEMA(this.injector)],
        ['reset', RESET_USER_PASSWORD_SCHEMA(this.injector)]
    ]);

    override ngOnInit() {
        this.schema = this.schemaMap.get(this.type)!;
        this.userSrv.getUser(this.item.userId ?? '').subscribe(res => {
            if (this.type !== 'reset') {
                this.schema!.properties!['postIds'].enum = res.data!.posts.map(item => {
                    return {
                        label: item.postName,
                        value: item.postId,
                        disabled: item.status === '1'
                    };
                });
                this.schema!.properties!['roleIds'].enum = res.data!.roles.map(item => {
                    return {
                        label: item.roleName,
                        value: item.roleId,
                        disabled: item.status === '1'
                    };
                });
                this.sf.refreshSchema();
            }
            this.item = { ...res.data?.user, postIds: res.data?.postIds, roleIds: res.data?.roleIds };
        });
    }

    protected makeParams(value: any): UserForm {
        let _temp = this.getValuesFormSf(value);
        if (this.type === 'edit') {
            return { ..._temp, userId: this.item.userId, userName: this.item.userName };
        }
        if (this.type === 'add') {
            return _temp;
        }
        return { ..._temp, userId: this.item.userId };
    }

    sendToServer(value: any): Observable<ApiResToComponent<UserVO>> {
        if (this.type === 'edit') {
            return this.userSrv.updateUser(value);
        }
        if (this.type === 'add') {
            return this.userSrv.addUser(value);
        }
        return this.userSrv.resetUserPwd(value);
    }
}
